package com.hzeport.bgs22emduty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.WebSocketSendInfoDTO;
import com.hzeport.bgs22emduty.dto.experience.*;
import com.hzeport.bgs22emduty.dto.messgeDistribute.*;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.enums.HideStatusEnum;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.outbound.db.ScreenMessageDistributeRepositoryImpl;
import com.hzeport.bgs22emduty.service.DutyScheduleInfoService;
import com.hzeport.bgs22emduty.service.ScreenMessageDistributeService;
import com.hzeport.bgs22emduty.service.SecurityLogService;
import com.hzeport.bgs22emduty.service.WebSocketSendInfoServer;
import com.hzeport.bgs22emduty.util.MessageSendUtil;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyMessageSaveVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.utils.IpUtils;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenMessageDistributeServiceImpl extends BaseServiceImpl<ScreenMessageDistributeRepositoryImpl, ScreenMessageDistribute> implements ScreenMessageDistributeService {

    @Resource
    private LoginCompoentService loginCompoentService;
    @Resource
    private AppendixRepository appendixRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;

    @Resource
    private WebSocketSendInfoServer webSocketSendInfoServer;
    @Resource
    private ScreenMessageDistributeHideRepository screenMessageDistributeHideRepository;
    @Resource
    private SecurityLogService securityLogService;
    @Override
    public Page<ScreenMessageDistribute> getScreenMessageDistributePage(ScreenMessageDistributeDTO dto) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenMessageDistribute> queryWrapper = new LambdaQueryWrapper<>();
        if (!userInfoDetailVO.getRole().contains("ZGGLY")) {
            List< ScreenMessageDistributeHide > distributeHides = screenMessageDistributeHideRepository.list(
                    new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                            .eq( ScreenMessageDistributeHide::getCustomId ,userInfoDetailVO.getCustomscode() ));
            if(!CollectionUtils.isEmpty( distributeHides )){
                List<String> ids = distributeHides.stream().map( ScreenMessageDistributeHide::getDistributeId ).collect( Collectors.toList());
                queryWrapper.in(ScreenMessageDistribute::getId, ids);
            }else {
                return new Page<>();
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(dto.getTimes())&&dto.getTimes().get(0)!=null){
            LocalDate localDate=LocalDate.parse(dto.getTimes().get(0));
            queryWrapper.ge(ScreenMessageDistribute::getCreateTime,localDate.atStartOfDay());
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(dto.getTimes())&&dto.getTimes().get(1)!=null){
            LocalDate localDate=LocalDate.parse(dto.getTimes().get(1));
            queryWrapper.le(ScreenMessageDistribute::getCreateTime,localDate.atTime(23,59,59));
        }
        if (!StringUtils.isEmpty(dto.getKeyWord())){
            queryWrapper.like(ScreenMessageDistribute::getTitle,dto.getKeyWord());
        }
        if (!StringUtils.isEmpty(dto.getCustomId())){
            queryWrapper.like(ScreenMessageDistribute::getCustomId,dto.getCustomId());
        }
        queryWrapper.orderByDesc(ScreenMessageDistribute::getIsTopping);
        queryWrapper.orderByDesc(ScreenMessageDistribute::getCreateTime);
        Page<ScreenMessageDistribute> page = repository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        if (userInfoDetailVO.getRole().contains("ZGGLY")) {
            page.getRecords().forEach(screenDutyWork-> {
                BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
                if (personInfo!=null){
                    screenDutyWork.setCreateBy(personInfo.getUsername());
                    screenDutyWork.setCreatePerson(personInfo.getUsername());
                }
            });
        }else {
            page.getRecords().forEach(screenDutyWork-> {
                BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
                if (personInfo!=null){
                    screenDutyWork.setCreateBy(personInfo.getUsername());
                    screenDutyWork.setCreatePerson(personInfo.getUsername());
                    ScreenMessageDistributeHide distributeHide =
                            screenMessageDistributeHideRepository.getOne( new LambdaQueryWrapper< ScreenMessageDistributeHide >().eq( ScreenMessageDistributeHide::getCustomId , userInfoDetailVO.getCustomscode() ).eq( ScreenMessageDistributeHide::getDistributeId , screenDutyWork.getId() ) );
                    screenDutyWork.setStatus(  distributeHide.getStatus() );
                }
            });
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveExperiences(ScreenMessageDistributeSaveDTO dto) throws Exception {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        ScreenMessageDistribute screenMessageDistribute = new ScreenMessageDistribute();
        BeanUtil.copyProperties(dto,screenMessageDistribute);
        if (dto.getMainBody()==null){
            throw new Exception("正文不能为空") ;
        }
        if (dto.getTitle()==null){
            throw new Exception("标题不能为空") ;
        }
        screenMessageDistribute.setMainBody(dto.getMainBody().replaceAll("<p>","").replaceAll("</p>",""));
        if (StringUtils.isEmpty(screenMessageDistribute.getId())) {
            screenMessageDistribute.setCreateBy(userInfoDetailVO.getUserId());
            screenMessageDistribute.setCreateTime(LocalDateTime.now());
            screenMessageDistribute.setUpdateBy(userInfoDetailVO.getUserId());
            screenMessageDistribute.setUpdateTime(LocalDateTime.now());
            screenMessageDistribute.setCustomId(String.join( "|" ,  dto.getCustomId()));
            List< String > deptInfos = baseDeptInfoRepository.list( new LambdaQueryWrapper< BaseDeptInfo >().in( BaseDeptInfo::getId ,
                            dto.getCustomId() ) ).stream().map( BaseDeptInfo::getDeptName ).collect( Collectors.toList());
            screenMessageDistribute.setCustomName(String.join( "|" ,  deptInfos));
            screenMessageDistribute.setStatus(HideStatusEnum.NOT_HIDED.getValue());
            screenMessageDistribute.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            repository.save(screenMessageDistribute);
            WebSocketSendInfoDTO webSocketSendInfoDTO=new WebSocketSendInfoDTO();
            webSocketSendInfoDTO.setMessage("总署总值班室发布1条值班通知，请及时办理！");
            webSocketSendInfoDTO.setScreenMessageDistribute(screenMessageDistribute);
            webSocketSendInfoDTO.setModule("MESSAGE_SCREEN_DISTRIBUTE");
            webSocketSendInfoServer.sendAllDistribute(webSocketSendInfoDTO);

        }else {
            ScreenMessageDistribute byId = repository.getById(screenMessageDistribute.getId());
            if (byId != null){
                screenMessageDistribute.setRecVersion(byId.getRecVersion());
            }
            screenMessageDistribute.setCustomId(String.join( "|" ,  dto.getCustomId()));
            List< String > deptInfos =
                    baseDeptInfoRepository.list( new LambdaQueryWrapper< BaseDeptInfo >().in( BaseDeptInfo::getId ,
                            dto.getCustomId() ) ).stream().map( BaseDeptInfo::getDeptName ).collect( Collectors.toList());
            screenMessageDistribute.setCustomName(String.join( "|" ,  deptInfos));
            screenMessageDistribute.setUpdateBy(userInfoDetailVO.getUserId());
            screenMessageDistribute.setUpdateTime(LocalDateTime.now());
            repository.updateById(screenMessageDistribute);

        }

        if (dto.getId() != null) {
            if ( org.springframework.util.CollectionUtils.isEmpty(dto.getCustomId())) {
                screenMessageDistributeHideRepository.remove(new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                       .eq(ScreenMessageDistributeHide::getDistributeId, dto.getId()));
            } else {
                screenMessageDistributeHideRepository.remove(new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                        .eq(ScreenMessageDistributeHide::getDistributeId, dto.getId())
                        .notIn(ScreenMessageDistributeHide::getCustomId, dto.getCustomId()));
            }
            List<ScreenMessageDistributeHide> list = screenMessageDistributeHideRepository.list(new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                    .eq(ScreenMessageDistributeHide::getDistributeId, dto.getId() ));
            List<String> couIds = list.stream().map(ScreenMessageDistributeHide::getCustomId).collect(Collectors.toList());
            List<String> customIds = dto.getCustomId().stream().filter(id -> !couIds.contains(id)).collect(Collectors.toList());
            List<ScreenMessageDistributeHide> screenMessageDistributeHides = new ArrayList<>();
            for ( String customId : customIds ) {
                ScreenMessageDistributeHide hide = new ScreenMessageDistributeHide();
                hide.setDistributeId( screenMessageDistribute.getId() );
                hide.setStatus( "0" );
                hide.setCreateBy(userInfoDetailVO.getUserId());
                hide.setCreateTime(LocalDateTime.now());
                hide.setUpdateBy(userInfoDetailVO.getUserId());
                hide.setUpdateTime(LocalDateTime.now());
                hide.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                hide.setCustomId( customId );
                screenMessageDistributeHides.add( hide );
            }
            screenMessageDistributeHideRepository.saveBatch( screenMessageDistributeHides );
        } else {
            List<ScreenMessageDistributeHide> screenMessageDistributeHides = new ArrayList<>();
            for ( String customId : dto.getCustomId() ) {
                ScreenMessageDistributeHide hide = new ScreenMessageDistributeHide();
                hide.setDistributeId( screenMessageDistribute.getId() );
                hide.setStatus( "0" );
                hide.setCreateBy(userInfoDetailVO.getUserId());
                hide.setCreateTime(LocalDateTime.now());
                hide.setUpdateBy(userInfoDetailVO.getUserId());
                hide.setUpdateTime(LocalDateTime.now());
                hide.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                hide.setCustomId( customId );
                screenMessageDistributeHides.add( hide );
            }
            screenMessageDistributeHideRepository.saveBatch( screenMessageDistributeHides );
        }

        List<FileVO> files = dto.getFiles();
        if (!CollectionUtils.isEmpty(files)) {
            files.forEach(fileVO -> {
                LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Appendix::getId, fileVO.getId()).set(Appendix::getRelevanceId, screenMessageDistribute.getId());
                appendixRepository.update(wrapper);
            });
        }
        return "1";
    }

    @Override
    public Object remove(ScreenMessageDistributeRemoveDTO screenMessageDistributeRemoveDTO) {
        return repository.removeById(screenMessageDistributeRemoveDTO.getId());
    }



    @Override
    public Object hide(ScreenMessageDistributeHideDTO screenMessageDistributeHideDTO) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        ScreenMessageDistribute screenMessageDistribute=repository.getById(screenMessageDistributeHideDTO.getId());
        if (userInfoDetailVO.getRole().contains("ZGGLY")) {
            screenMessageDistribute.setStatus(screenMessageDistributeHideDTO.getStatus());
            return repository.updateById(screenMessageDistribute);
        }else {
            List< ScreenMessageDistributeHide > distributeHides = screenMessageDistributeHideRepository.list(
                    new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                            .eq( ScreenMessageDistributeHide::getCustomId ,userInfoDetailVO.getCustomscode() )
                            .eq( ScreenMessageDistributeHide::getDistributeId ,screenMessageDistributeHideDTO.getId( )
            ));
            List< ScreenMessageDistributeHide > list = distributeHides.stream().map( item -> {
                item.setStatus( screenMessageDistributeHideDTO.getStatus() );
                return item;
            } ).collect( Collectors.toList() );
            return screenMessageDistributeHideRepository.updateBatchById( list );
        }
    }

    @Override
    public Object detail(String id) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        ScreenMessageDistribute screenDutyWork=repository.getById(id);
        if (screenDutyWork.getCreateBy()!=null) {
            BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
            if (personInfo!=null){
                screenDutyWork.setCreateBy(personInfo.getUsername());
                screenDutyWork.setCreatePerson(personInfo.getUsername());
            }
        }
        ScreenMessageDistributeDetailDTO screenDutyWorkDetailDTO=new ScreenMessageDistributeDetailDTO();
        BeanUtils.copyProperties(screenDutyWork,screenDutyWorkDetailDTO);
        List<FileVO> fileVOS = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, id))
                .stream().map(appendix -> {
                    FileVO fileVO = new FileVO();
                    BeanUtils.copyProperties(appendix,fileVO);
                    return fileVO;
                }).collect(Collectors.toList());
            screenDutyWorkDetailDTO.setCustomId( Arrays.asList( screenDutyWork.getCustomId(  ).split( "\\|" ) ));

        screenDutyWorkDetailDTO.setFiles(fileVOS);
        return screenDutyWorkDetailDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult savels( ScreenDutyMessageSaveVO dto, HttpServletRequest request ) {
//        String customIds=dto.getCustomId();
//        String[] temp=customIds.split("\\|");
//        for (String customId:temp) {
            ScreenMessageDistribute screenMessageDistribute = new ScreenMessageDistribute();
//            BaseDeptInfo custom=baseDeptInfoRepository.getById(customId);
            BeanUtil.copyProperties(dto, screenMessageDistribute);
            if (StringUtils.isEmpty(screenMessageDistribute.getId())) {
                screenMessageDistribute.setCreateBy(dto.getCreatePerson());
                screenMessageDistribute.setCreateTime(LocalDateTime.now());
                screenMessageDistribute.setUpdateBy(dto.getCreatePerson());
                screenMessageDistribute.setUpdateTime(LocalDateTime.now());
//                screenMessageDistribute.setCustomId(customId);
//                screenMessageDistribute.setCustomName(custom.getDeptName());
                screenMessageDistribute.setStatus(HideStatusEnum.NOT_HIDED.getValue());
                screenMessageDistribute.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());

                repository.save(screenMessageDistribute);
                WebSocketSendInfoDTO webSocketSendInfoDTO=new WebSocketSendInfoDTO();
                webSocketSendInfoDTO.setMessage("总署总值班室发布1条值班通知，请及时办理！");
                webSocketSendInfoDTO.setScreenMessageDistribute(screenMessageDistribute);
                webSocketSendInfoDTO.setModule("MESSAGE_SCREEN_DISTRIBUTE");
                webSocketSendInfoServer.sendAllDistribute(webSocketSendInfoDTO);
            } else {
                ScreenMessageDistribute byId = repository.getById(screenMessageDistribute.getId());
                if (byId != null){
                    screenMessageDistribute.setRecVersion(byId.getRecVersion());
                }
                screenMessageDistribute.setUpdateBy(dto.getCreatePerson());
                screenMessageDistribute.setUpdateTime(LocalDateTime.now());
                repository.updateById(screenMessageDistribute);
            }
        if (dto.getId() != null) {
            List<String> customIds=Arrays.asList(dto.getCustomId().split( "\\|" ));
            if ( org.springframework.util.CollectionUtils.isEmpty(customIds)) {
                screenMessageDistributeHideRepository.remove(new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                        .eq(ScreenMessageDistributeHide::getDistributeId, dto.getId()));
            } else {
                screenMessageDistributeHideRepository.remove(new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                        .eq(ScreenMessageDistributeHide::getDistributeId, dto.getId())
                        .notIn(ScreenMessageDistributeHide::getCustomId, customIds));
            }
            List<ScreenMessageDistributeHide> list = screenMessageDistributeHideRepository.list(new LambdaQueryWrapper<ScreenMessageDistributeHide>()
                    .eq(ScreenMessageDistributeHide::getDistributeId, dto.getId() ));
            List<String> couIds = list.stream().map(ScreenMessageDistributeHide::getCustomId).collect(Collectors.toList());
            customIds = customIds.stream().filter(id -> !couIds.contains(id)).collect(Collectors.toList());
            List<ScreenMessageDistributeHide> screenMessageDistributeHides = new ArrayList<>();
            for ( String customId : customIds ) {
                ScreenMessageDistributeHide hide = new ScreenMessageDistributeHide();
                hide.setDistributeId( screenMessageDistribute.getId() );
                hide.setStatus( "0" );
                hide.setCreateBy(dto.getCreatePerson());
                hide.setCreateTime(LocalDateTime.now());
                hide.setUpdateBy(dto.getCreatePerson());
                hide.setUpdateTime(LocalDateTime.now());
                hide.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                hide.setCustomId( customId );
                screenMessageDistributeHides.add( hide );
            }
            screenMessageDistributeHideRepository.saveBatch( screenMessageDistributeHides );
        } else {
            List<ScreenMessageDistributeHide> screenMessageDistributeHides = new ArrayList<>();
            List<String> customIds=Arrays.asList(dto.getCustomId().split( "\\|" ));
            for ( String customId : customIds ) {
                ScreenMessageDistributeHide hide = new ScreenMessageDistributeHide();
                hide.setDistributeId( screenMessageDistribute.getId() );
                hide.setStatus( "0" );
                hide.setCreateBy(dto.getCreatePerson());
                hide.setCreateTime(LocalDateTime.now());
                hide.setUpdateBy(dto.getCreatePerson());
                hide.setUpdateTime(LocalDateTime.now());
                hide.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                hide.setCustomId( customId );
                screenMessageDistributeHides.add( hide );
            }
            screenMessageDistributeHideRepository.saveBatch( screenMessageDistributeHides );
        }
//        }
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy(dto.getCreatePerson());
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress( IpUtils.getIpAddr(request));
        operateLog.setSDescription( JSON.toJSONString( dto ) );
        operateLog.setSModule("ZBXXLS");
        operateLog.setSTitle("ZBBC");
        securityLogService.save(operateLog);
        return BaseResult.ok();
    }

    @Override
    public BaseResult< String > topping( ScreenMessageDistributeHideDTO dto , ScreenMessageDistributeHideDTO dto1 ) {
        ScreenMessageDistribute screenMessageDistribute = getById( dto.getId() );
        if ( "0".equals( screenMessageDistribute.getIsTopping() ) ) {
            screenMessageDistribute.setIsTopping( "1" );
        }else {
            screenMessageDistribute.setIsTopping( "0" );
        }
        updateById( screenMessageDistribute );
        return BaseResult.ok(null,"更改成功");
    }
}
